#!/usr/bin/env python
# coding: utf-8

import freeswitch
from cloudcallRedis2 import rdc
import time
import random
import demjson

#此运行在python2 上面，编码方面不太一样

###
# rdc.get_state()
# rdc.get_cop_num('20358')
# rdc.get_last_call_info('LastCallInfo:02023398853:13724059427')

def handler(session, args):  # args is string
    session.setAutoHangup(False)
    uuid = session.getVariable("uuid")

    if args is None:
        freeswitch.console_log("info", "call %s has no target call number in args param\n" % uuid)
        session.hangup("UNALLOCATED_NUMBER")
        return

    freeswitch.console_log("info", "call %s args string is: %s \n" % (uuid, args))

    X_uuid = session.getVariable("sip_h_X-uuid")
    X_create_user_id = session.getVariable("sip_h_X-create_user_id")
    X_city = session.getVariable("sip_h_X-city")

    if X_create_user_id is None or X_city is None or X_uuid is None:
        freeswitch.console_log("info", "X_uuid and X_create_user_id and X_uuid is required !")
        session.hangup("UNALLOCATED_NUMBER")
        return

    freeswitch.console_log("info", "city type str: %s \n" % isinstance(X_city, str))
    freeswitch.console_log("info", "X_create_user_id type str: %s \n" % isinstance(X_create_user_id, str))

    X_uuid = X_uuid.strip()
    X_create_user_id = X_create_user_id.strip()
    X_city = X_city.strip()

    freeswitch.consoleLog("info", "call %s extend params: X_uuid: %s, X_create_user_id: %s, X_city: %s \n" %
                          (uuid, X_uuid, X_create_user_id, X_city))
    # unicode
    show_num = rdc.get_cop_num(X_create_user_id, X_city)
    show_num = show_num.encode('utf-8')
    freeswitch.console_log("err", "show_num: %s, type: %s \n" % (show_num.encode('utf-8'), type(show_num)))
    # show_num_dict = rdc.get_cop_show_num_dict(X_create_user_id)
    # freeswitch.console_log("info",demjson.encode(show_num_dict,'utf-8'))

    # show_num = "1002"
    if show_num is None:
        freeswitch.console_log("info", "get show_num from redis cluster is None,"
                                       "with user_id: %,city: % \n" % (X_create_user_id, X_city))
        session.hangup("UNALLOCATED_NUMBER")
        return

    session.setVariable("continue_on_fail", "false")
    session.setVariable("hangup_after_bridge", "true")
    session.setVariable("jitterbuffer_msec", "260:400:20")
    session.execute("export", "session_id=${uuid}")
    session.execute("export", "call_timeout=60")
    # TODO
    session.setHangupHook("myHangupHook", "test myHangupHook")
    # save record file
    today = time.strftime("%Y%m%d", time.localtime())

    record_save_base_paths = ["/cloudcall_file/rec_20050/freeswitchRecordFile/",
                              "/cloudcall_file/rec_20051/freeswitchRecordFile/"]
    path = random.choice(record_save_base_paths) + today + "/" + uuid + ".wav"
    freeswitch.console_log("info", "choice path: %s" % path)
    session.execute("export", "nolocal:execute_on_answer=record_session " + path)

    call_str = "{origination_caller_id_number=%s,origination_caller_id_name=%s}" \
               "sofia/external/98%s@10.41.46.57:5060" % (show_num, show_num, args)
    freeswitch.console_log("info", "bridge string is: %s \n" % call_str)
    # session.execute("bridge", "user/%s" % args)
    session.execute("bridge", call_str)
    session.hangup()


def myHangupHook(session, status, args):
    freeswitch.consoleLog("info", "myHangupHook: " + status + "\n")